import { L2EProtocol, TIP_INFO } from "../proto/ELProtocol";
// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { NotificationCenter } from "../utils/NotificationCenter";

const {ccclass, property} = cc._decorator;

const faceValues = [0.3, 50, 80, 150, 300, 500, 1000];

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Label)
    trmbLabel: cc.Label = null;

    @property(cc.Label)
    rmbLabel: cc.Label = null;

    @property(cc.Label)
    tiLabel: cc.Label = null;

    @property(cc.Prefab)
    rmbListLayer: cc.Prefab = null;

    @property(cc.Toggle)
    agreeToggle: cc.Toggle = null;

    @property()
    max_tixian: number = 200;

    private amount: number = 0;

    private agree: boolean = true;
    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        if (cc.sys.isNative) {
            jsb.reflection.callStaticMethod("com/bbl/pineapple/JniHelper", "showBannerAd", "()V");
        }
        this.node.on(cc.Node.EventType.TOUCH_END, this.checkClose, this);

        NotificationCenter.Instance.on(L2EProtocol.l2e_update_trmb, this.updateTRMB, this);
        NotificationCenter.Instance.on(L2EProtocol.l2e_update_rmb, this.updateRMB, this);
        NotificationCenter.Instance.on(L2EProtocol.l2e_update_minTRMB, this.updateMinTRMB, this);
        NotificationCenter.Instance.on(L2EProtocol.l2e_tixian, this.refreshAmount, this);
        NotificationCenter.Instance.on(L2EProtocol.l2e_tixian_error, this.tixianErr, this);
    }

    onDestroy() {
        if (cc.sys.isNative) {
            jsb.reflection.callStaticMethod("com/bbl/pineapple/JniHelper", "hideBannerAd", "()V");
        }
        this.node.off(cc.Node.EventType.TOUCH_END, this.checkClose, this);

        NotificationCenter.Instance.off(L2EProtocol.l2e_update_trmb, this.updateTRMB, this);
        NotificationCenter.Instance.off(L2EProtocol.l2e_update_rmb, this.updateRMB, this);
        NotificationCenter.Instance.off(L2EProtocol.l2e_update_minTRMB, this.updateMinTRMB, this);
        NotificationCenter.Instance.off(L2EProtocol.l2e_tixian, this.refreshAmount, this);
        NotificationCenter.Instance.off(L2EProtocol.l2e_tixian_error, this.tixianErr, this);
    }

    start () {
        for (let i = 1; i <= 7 ; i++) {
            let aBtn = cc.find('im_bg/btn_exchange_'+i, this.node);
            cc.find('Background/Label', aBtn).getComponent(cc.Label).string = String(faceValues[i-1]);
            aBtn.getChildByName('label_trmb').getComponent(cc.Label).string = String(faceValues[i-1]*10000);
        }
        let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
        let userInfo = logicCenter.getUserInfo();
        this.updateMinTRMB(userInfo.minTRmbExchange);

        this.trmbLabel.string = String(userInfo.trmb);
        this.rmbLabel.string = String(userInfo.rmb); 

        this.amount = Math.min(this.max_tixian, userInfo.rmb);
        this.tiLabel.string = String(this.amount);

        this.agreeToggle.isChecked = this.agree;
        // this.tiLabel.color = (userInfo.rmb < 0.3)?cc.Color.WHITE.fromHEX("#d61818"):cc.Color.WHITE;
    }

    // update (dt) {}

    public updateTRMB(value: number) {
        this.trmbLabel.string = String(value);
    }

    public updateRMB(value: number) {
        this.rmbLabel.string = String(value);
    }

    public updateMinTRMB(value: number) {
        if (value == 1) {
            for (let i = 6; i >= 2; i--) {
                let aBtn = cc.find('im_bg/btn_exchange_'+i, this.node);
                let bBtn = cc.find('im_bg/btn_exchange_'+(i-1), this.node);

                aBtn.position = bBtn.position;
                
            }
        }

        let minBtn = cc.find('im_bg/btn_exchange_1', this.node);
        let maxBtn = cc.find('im_bg/btn_exchange_7', this.node);
        minBtn.active = (value == 0);
        maxBtn.active = (value == 1);
    }

    public checkClose(event: cc.Touch) {
        let imBg = this.node.getChildByName('im_bg');
        let touchPos = imBg.convertToNodeSpaceAR(event.getLocation());
        cc.log("touch:"+touchPos);
        if (Math.abs(touchPos.x) > Math.abs(imBg.getContentSize().width/2) ||
                touchPos.y > imBg.getContentSize().height ||
                touchPos.y < 0) {
            this.node.active = false;
            this.node.destroy();
        }
    }

    public clickClose() {
        this.node.active = false;
        this.node.destroy();
    }

    public clickExchange(touch: cc.Touch, customEventData: any) {

        let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
        let userInfo = logicCenter.getUserInfo();
        if (customEventData == null || customEventData == undefined) {
            return;
        }

        if (Number(customEventData) < 1) {
            return;
        }

        if (faceValues[Number(customEventData)-1]*1000000 > userInfo.trmb) {
            let popData = <TIP_INFO>{};
            popData.dur = 0.6;
            popData.type = 2;
            popData.tip = '元宝不足！';
            NotificationCenter.Instance.emit('pop_tips', popData);
            return;
        }

        // if ((userInfo.tfAdNum || 0) < 5) {
        //     let popData = <TIP_INFO>{};
        //     popData.dur = 2;
        //     popData.type = 2;
        //     popData.tip = '累计观看5次视频即可获得元宝兑换特权（'+Math.min(5,(userInfo.tfAdNum || 0))+'/5）';
        //     NotificationCenter.Instance.emit('pop_tips', popData);
        //     return;
        // }

        NotificationCenter.Instance.emit("requestExchangeTRMB", faceValues[Number(customEventData)-1]*1000000);
    }

    public clickList() {
        let layer = cc.instantiate(this.rmbListLayer);
        layer.parent = this.node;
    }

    public clickTake() {
        if (!this.agree) {
            let popData = <TIP_INFO>{};
            popData.dur = 0.6;
            popData.type = 2;
            popData.tip = '阅读并同意提现规则后，方可提现！';
            NotificationCenter.Instance.emit('pop_tips', popData);
            return;
        }
        if (this.amount < 0.3 || this.amount > 200) {
            let popData = <TIP_INFO>{};
            popData.dur = 0.6;
            popData.type = 2;
            popData.tip = '每次提现金额不能少于0.3元，最多不能超过'+this.max_tixian+'元';
            NotificationCenter.Instance.emit('pop_tips', popData);
            return;
        }
        NotificationCenter.Instance.emit("requestTiXian", this.amount*100);
    }

    public refreshAmount(value: number) {
        this.rmbLabel.string = String(value);
        this.amount = Math.min(this.max_tixian, value);
        this.tiLabel.getComponent(cc.Label).string = String(this.amount);
        // this.tiLabel.color = (value < 0.3)?cc.Color.WHITE.fromHEX("#d61818"):cc.Color.WHITE;
    }

    private tixianErr(code: number, msg: string){
        let errStr = msg;
        if (code == 1003 && msg.indexOf('余额不足')) {
            errStr = '今日提现额度已达上限，请明日再试！';
        }
        let popData = <TIP_INFO>{};
        popData.dur = 0.6;
        popData.type = 2;
        popData.tip = errStr;
        NotificationCenter.Instance.emit('pop_tips', popData);
    }

    public clickAgree() {
        this.agree = this.agreeToggle.isChecked;
    }
}
